import React from "react";
import { ColumnProps } from "antd/es/table";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import {
  Badge,
  Button,
  ConfigProvider,
  Divider,
  Popconfirm,
  Table,
  Tooltip,
  message,
} from "antd";
import { SearchForm } from "@/components/SearchForm";
import { useGetUserNotificationResult } from "@/pages/user/api/useGetUser";
import {
  deleteById,
  updateState as updateStateApi,
} from "@/pages/user/service/notification";
import useLocalStorage from "@/hooks/useLocalStorage";
import { RQ_GET_USER_NOTIFICATION } from "@/service/key";
import { NotificationDataType } from "../../types";
import { Save } from "./save";

const NotificationView = () => {
  // const [page, setPage] = React.useState(1);
  // const [pageSize, setPageSIze] = React.useState(10);
  // const [subscriberNameParam, SetsubscriberNameParam] = React.useState("");
  const [page, setPage] = useLocalStorage("page", 1);
  const [pageSize, setPageSIze] = useLocalStorage("pageSize", 10);
  const [subscriberNameParam, SetsubscriberNameParam] = useLocalStorage(
    "subscriberNameParam",
    "",
  );
  const [saveVisible, setSaveVisible] = React.useState<boolean>(false);
  const [current, setCurrent] = React.useState<NotificationDataType>();

  const { isLoading, data } = useGetUserNotificationResult({
    pageNum: page,
    pageSize: pageSize,
    subscriberName: subscriberNameParam,
  });

  const columns: ColumnProps<NotificationDataType>[] = [
    {
      title: "订阅类型",
      dataIndex: "subscriberType",
    },
    {
      title: "订阅主题",
      dataIndex: "topicProvider",
    },
    {
      title: "订阅名称",
      dataIndex: "subscriberName",
    },
    {
      title: "状态",
      dataIndex: "state",
      render: (_, record) => {
        return (
          <Tooltip title={record.state}>
            {record.state === "订阅中" ? (
              <Badge status="success" />
            ) : (
              <Badge status="default" />
            )}
          </Tooltip>
        );
      },
    },
    {
      title: "操作",
      render: (_, record) => {
        return (
          <>
            <a
              onClick={() => {
                setSaveVisible(true);
                setCurrent(record);
              }}
            >
              配置
            </a>
            <Divider type="vertical" />
            {record.state !== "订阅中" ? (
              <>
                <a
                  onClick={(event) => {
                    event.preventDefault();
                    updateState.mutate(record.id);
                  }}
                >
                  开启
                </a>
                <Divider type="vertical" />
              </>
            ) : (
              <>
                <a
                  onClick={(event) => {
                    event.preventDefault();
                    updateState.mutate(record.id);
                  }}
                >
                  关闭
                </a>
                <Divider type="vertical" />
              </>
            )}
            <Popconfirm
              title="删除此订阅？"
              onConfirm={() => remove.mutate(record.id)}
            >
              <a>删除</a>
            </Popconfirm>
          </>
        );
      },
    },
  ];

  // ["订阅中", "已停止"]
  const onTableChange = (pagination: any, filters: any, sorter: any) => {
    console.log("pagination :", pagination);
    setPage(pagination.current);
  };

  const handleSearch = () => {
    queryCLient.refetchQueries([
      RQ_GET_USER_NOTIFICATION,
      page,
      pageSize,
      subscriberNameParam,
    ]);
  };

  const queryCLient = useQueryClient();
  const updateState = useMutation(
    (id: string) => {
      return updateStateApi(id);
    },
    {
      onSuccess: (data) => {
        if (data.data.dataInfo.state === "订阅中") {
          message.success("开启订阅成功");
        } else {
          message.success("关闭订阅成功");
        }
        handleSearch();
      },
    },
  );
  const remove = useMutation(
    (id: string) => {
      return deleteById(id);
    },
    {
      onSuccess: (data) => {
        message.success("删除成功");
        handleSearch();
      },
    },
  );

  return (
    <div>
      <SearchForm
        searchList={[
          {
            tagFName: "input",
            key: "subscriberNameParam",
            label: "查询",
          },
          {
            tagFName: "datePicker",
            key: "datepickerItem",
            label: "创建日期",
          },
          // {
          //   tagFName: "select",
          //   key: "site",
          //   label: "站点",
          //   sf_defaultValue: null,
          //   placeholder: "请选择站点",
          //   sf_selectlist: [
          //     {
          //       id: 0,
          //       value: "站点1",
          //     },
          //     {
          //       id: 1,
          //       value: "站点2",
          //     },
          //   ],
          // },
          {
            tagFName: "treeSelect",
            key: "state",
            label: "状态",
            sf_defaultValue: null,
            placeholder: "请选择状态",
            sf_selectlist: [
              {
                id: 0,
                value: "类型",
                children: [
                  {
                    id: 10,
                    value: "使用中",
                  },
                  {
                    id: 11,
                    value: "已停止",
                  },
                ],
              },
              {
                id: 1,
                value: "状态2",
                children: [
                  {
                    id: 20,
                    value: "状态21",
                  },
                  {
                    id: 21,
                    value: "状态22",
                  },
                ],
              },
            ],
          },
        ]}
        onSearch={(v: any) => {
          console.log("search :", v);
          SetsubscriberNameParam(v["subscriberNameParam"]);
          // handleSearch();
        }}
        // 防抖没成功
        // autoSearch={true}
      />
      <div style={{ margin: 10 }}>
        <Button
          type="primary"
          onClick={() => {
            setCurrent(undefined);
            setSaveVisible(true);
          }}
        >
          添加订阅
        </Button>
      </div>
      <ConfigProvider
        theme={{
          token: {
            // sizeStep: 3,
            // sizeUnit: 3,
          },
          // components: {
          //   Table: {
          //     paddingContentVertical: 4,
          //     paddingContentVerticalLG: 6,
          //   },
          // },
        }}
      >
        <Table
          loading={isLoading}
          rowKey="id"
          dataSource={data?.data.dataInfo}
          columns={columns}
          onChange={onTableChange}
          pagination={{
            current: data?.data.pageInfo?.pageNum,
            total: data?.data.pageInfo?.totalCount,
            pageSize: data?.data.pageInfo?.pageSize,
            showQuickJumper: true,
            showSizeChanger: false,
            showTotal: (total: number) =>
              `共 ${total} 条记录 第  ${data?.data.pageInfo?.pageNum}/${data?.data.pageInfo?.totalPageNum}页`,
          }}
        />
      </ConfigProvider>
      {saveVisible && (
        <Save
          title="配置订阅"
          data={current}
          close={() => {
            setSaveVisible(false);
            handleSearch();
          }}
        />
      )}
    </div>
  );
};

export default NotificationView;
